package fun.ticsmyc.consumer.controller;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import fun.ticsmyc.common.pojo.Book;
import fun.ticsmyc.common.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;

/**
 * @author Ticsmyc
 * @date 2020-03-21 15:26
 */
@Controller
public class BookController {
    @Resource
    @Reference
    private BookService bookService;

    @GetMapping("getBookById")
    public ResponseEntity<Book> selectOneBook(@RequestParam("id")Integer id){
        Book res = null;
        if(id != null){
            res =this.bookService.queryById(id);
        }
        if(res != null){
            return ResponseEntity.ok(res);
        }else{
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("addBook")
    public ResponseEntity<Book> addOneBook(@RequestParam("name")String name) throws UnsupportedEncodingException {

        if(name != null){
            if(this.bookService.add(name)){
                return ResponseEntity.ok().build();
            }else{
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        }else{
            return ResponseEntity.badRequest().build();
        }
    }

    @DeleteMapping("deleteBook")
    public ResponseEntity<Book> deleteOneBook(@RequestParam("id")Integer id){
        if(id !=null){
            if(this.bookService.delete(id)){
                return ResponseEntity.ok().build();
            }else{
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        }else{
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("getBooksByName")
    public ResponseEntity<List<Book>> getBooks(@RequestParam("name")String name){
        if(name !=null){
            List<Book> res= this.bookService.queryByName(name);
            if(CollectionUtils.isNotEmpty(res)){
                return ResponseEntity.ok(res);
            }else{
                return ResponseEntity.notFound().build();
            }
        }else{
            return ResponseEntity.badRequest().build();
        }
    }

}
